package service

import (
	"context"
	"goframe-zc/dto"
	"goframe-zc/internal/dao"
	"math"

	"github.com/gogf/gf/v2/os/gtime"
)

type orderService struct{}

var Order = &orderService{}

// GetOrderList 获取订单列表
func (s *orderService) GetOrderList(ctx context.Context, req *dto.OrderListReq, userId uint) (*dto.OrderListRes, error) {
	// 1. 查询订单基本信息
	orderList, total, err := s.queryOrderList(ctx, req, userId)
	if err != nil {
		return nil, err
	}

	// 2. 如果没有订单数据，直接返回空结果
	if len(orderList) == 0 {
		return &dto.OrderListRes{
			Page:       req.Page,
			Limit:      req.Limit,
			Total:      0,
			TotalPages: 0,
			List:       []dto.OrderListItem{},
		}, nil
	}

	// 3. 获取订单ID集合
	orderIds := make([]int64, 0, len(orderList))
	for _, order := range orderList {
		orderIds = append(orderIds, order.OrderId)
	}

	// 4. 批量查询订单商品
	orderGoodsMap, err := s.queryOrderGoods(ctx, orderIds)
	if err != nil {
		return nil, err
	}

	// 5. 组装订单商品数据
	for i, order := range orderList {
		if goodsList, ok := orderGoodsMap[order.OrderId]; ok {
			orderList[i].GoodsList = goodsList
		} else {
			orderList[i].GoodsList = []dto.OrderGoodsItem{}
		}
	}

	// 6. 计算总页数
	totalPages := int(math.Ceil(float64(total) / float64(req.Limit)))

	return &dto.OrderListRes{
		Page:       req.Page,
		Limit:      req.Limit,
		Total:      total,
		TotalPages: totalPages,
		List:       orderList,
	}, nil
}

// queryOrderList 查询订单基本信息
func (s *orderService) queryOrderList(ctx context.Context, req *dto.OrderListReq, userId uint) ([]dto.OrderListItem, int, error) {
	// 构建查询条件
	query := dao.ZcOrder.Ctx(ctx).Where("user_id", userId)

	// 添加状态筛选
	if req.Status > 0 {
		query = query.Where("status", req.Status)
	}

	// 分页查询
	page := req.Page
	pageSize := req.Limit

	// 查询总数
	total, err := query.Count()
	if err != nil {
		return nil, 0, err
	}

	// 查询订单列表
	var orders []struct {
		Id         int64       `json:"id"`
		OrderSn    string      `json:"order_sn"`
		CreateTime *gtime.Time `json:"create_time"`
		Status     int         `json:"status"`
		SumFee     int         `json:"sum_fee"`
		PayEndTime *gtime.Time `json:"pay_end_time"` // 支付截止时间
	}

	err = query.
		Fields("id, order_sn, create_time, status, sum_fee").
		Page(page, pageSize).
		OrderDesc("id").
		Scan(&orders)

	if err != nil {
		return nil, 0, err
	}

	// 转换为OrderListItem列表
	orderList := make([]dto.OrderListItem, 0, len(orders))
	currentTime := gtime.Now()

	for _, o := range orders {
		// 计算支付等待时间（秒）
		var payWaitTime int64
		if o.PayEndTime != nil && o.Status == 1 {
			payWaitTime = int64(o.PayEndTime.Timestamp() - currentTime.Timestamp())
			if payWaitTime < 0 {
				payWaitTime = 0
			}
		}

		orderList = append(orderList, dto.OrderListItem{
			OrderId:     o.Id,
			OrderSn:     o.OrderSn,
			CreateTime:  o.CreateTime,
			Status:      o.Status,
			SumFee:      o.SumFee,
			PayWaitTime: payWaitTime,
		})
	}

	return orderList, total, nil
}

// queryOrderGoods 查询订单商品信息
func (s *orderService) queryOrderGoods(ctx context.Context, orderIds []int64) (map[int64][]dto.OrderGoodsItem, error) {
	// 查询订单商品关联数据
	var goodsData []struct {
		OrderId    int64  `json:"order_id"`
		GoodsId    int64  `json:"goods_id"`
		GoodsImg   string `json:"goods_img"`
		GoodsName  string `json:"goods_name"`
		GoodsPrice int    `json:"goods_price"`
		Num        int    `json:"num"`
	}

	err := dao.ZcOrderInfo.Ctx(ctx).
		As("o").
		Where("o.order_id", orderIds).
		LeftJoin("zc_mall_goods AS g", "g.id = o.goods_id").
		Fields(`
			o.order_id,
			o.goods_id,
			g.goods_img,
			g.goods_name,
			g.goods_price,
			o.goods_num num
		`).
		Scan(&goodsData)

	if err != nil {
		return nil, err
	}

	// 按订单ID分组商品
	orderGoodsMap := make(map[int64][]dto.OrderGoodsItem)

	for _, g := range goodsData {
		item := dto.OrderGoodsItem{
			GoodsImg:   g.GoodsImg,
			GoodsName:  g.GoodsName,
			GoodsPrice: g.GoodsPrice,
			Num:        g.Num,
		}

		if list, ok := orderGoodsMap[g.OrderId]; ok {
			orderGoodsMap[g.OrderId] = append(list, item)
		} else {
			orderGoodsMap[g.OrderId] = []dto.OrderGoodsItem{item}
		}
	}

	return orderGoodsMap, nil
}
